<template>
  <Row style="background: #fff; direction: rtl">
    <Button type="primary" shape="round" @click="onCopyScript" style="direction: ltr"><CopyFilled /> 复制脚本</Button>
  </Row>
  <Row>
    <pre :style="contentStyle" ref="scripts">{{ ddl }}</pre>
  </Row>
</template>

<script setup>
  import { useStore } from 'vuex';
  import { ref, inject, watch, computed, onMounted } from 'vue';
  import { Row, Button } from 'ant-design-vue';
  import { CopyFilled } from '@ant-design/icons-vue';

  const $store = useStore();
  const $http = inject('$http');
  const $message = inject('$message');
  const $copyText = inject('$copyText');

  const props = defineProps({
    dbIndex: String,
    dbType: String,
    schema: String,
    tableName: String
  });

  const ddl = ref('');

  const contentStyle = computed(() => {
    let maxHeight = $store.state.area.content.height - 130 + 'px';

    return {
      'min-height': maxHeight,
      'max-height': maxHeight
    };
  });

  watch(
    () => props.tableName,
    () => GetTableDDL()
  );

  function GetTableDDL() {
    if (props.dbIndex && props.schema && props.tableName) {
      $http.get(`/api/db/${props.dbIndex}/${props.schema}/${props.tableName}/ddl`).then(res => (ddl.value = res.data['Create Table']));
    }
  }

  function onCopyScript() {
    $copyText(ddl.value).then(() => {
      $message.success('脚本已复制！');
    });
  }

  onMounted(() => {
    GetTableDDL();
  });
</script>
